// 主客户ID
var mainCustomerId=sessionStorage.getItem("mainCustomerId")
// 操作人ID
var  operateUserId = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID
// 操作人账号
var  operateUserName =JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
// 临采商品数据源
var dataSource = [];
// 弹窗临采商品数据源
var popDataSource = [];
// 获取接口
var getData = {
  // 获取临采商品查询列表
  searchTemporaryData:function(){
    var skuCode = $("#skuCode").val();//临采SKU编码
    var skuName = $("#skuName").val();//临采SKU名称
    var params = {
      mainCustomerId: mainCustomerId,//主客户id
      skuCode:skuCode,//临采SKU编码
      skuName:skuName,//临采SKU名称
      relationStatus:10, //10 是页面查询入口参数  20 是弹窗的查询入口参数
      pageNum:1,
      pageSize:10,
    }
    // 获取输入框的输入信息
    $.ajax({
      url:root.member.queryTempPurchaseSkuList,
      cache: false,  //禁用缓存
      type: "POST",
      dataType:'json',
      contentType: "application/json",
      data: JSON.stringify(params),
      success: function (data) {
        if(data.errorCode == 0 && data.data.data.length >0){
          renderData.tableLists(data.data);
          $(".M-box4").pagination({
            pageCount: data.data.pageCount,
            jump: true,
            coping: true,
            prevContent: '上页',
            nextContent: '下页',
            callback:function(api){
              params.pageNum = api.getCurrent()
              $.ajax({
                url:root.member.queryTempPurchaseSkuList,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify(params),
                success:function(data){
                  renderData.tableLists(data.data);
                },
                error:function(msg){
                  $.Huimodalalert('失败！',2000);
                }
              })
            }
          })
        } else {
          $(".M-box4").pagination({
            pageCount:0
          })
          renderData.tableLists(data.data);
        }

      },
      error: function (msg) {
        $.Huimodalalert(msg,2000);
      }
    })
  },
  // 弹窗--获取弹窗临采商品的列表
  popSearchTemporaryData:function(){
    var popskuCode = $("#popskuCode").val();//临采SKU编码
    var popskuName = $("#popskuName").val();//临采SKU名称
    var params = {
      mainCustomerId: mainCustomerId,//主客户id
      skuCode:popskuCode,//临采SKU编码
      skuName:popskuName,//临采SKU名称
      relationStatus:20,//10 是页面查询入口参数  20 是弹窗的查询入口参数
      pageNum:1,
      pageSize:10,
    }
    // 获取输入框的输入信息
    $.ajax({
      url:root.member.queryTempPurchaseSkuList,
      cache: false,  //禁用缓存
      type: "POST",
      dataType:'json',
      contentType: "application/json",
      data: JSON.stringify(params),
      success: function (data) {
        if(data.errorCode == 0 && data.data.data.length >0){
          renderData.popTableLists(data.data)
          $(".M-box3").pagination({
            pageCount: data.data.pageCount,
            jump: true,
            coping: true,
            prevContent: '上页',
            nextContent: '下页',
            callback:function(api){
              params.pageNum = api.getCurrent()
              $.ajax({
                url:root.member.queryTempPurchaseSkuList,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify(params),
                success:function(data){
                  renderData.popTableLists(data.data);
                },
                error:function(msg){
                  $.Huimodalalert('失败！',2000);
                }
              })
            }
          })
        }else{
          $(".M-box3").pagination({
            pageCount:0
          })
          renderData.popTableLists(data.data);
        }

      },
      error: function (msg) {
        $.Huimodalalert(msg,2000);
      }
    })
  },
  // 点击弹窗选择 接口区分relationStatus  10是新增及选择  20是删除操作
  addOrCancel:function(relationStatus,skuCode){
    var params = {
       mainCustomerId:mainCustomerId,
      relationStatus:relationStatus
    }
    if(Array.isArray(skuCode)){
      params.updateIds = skuCode
    }else{
      var updateId = [];
      updateId.push(skuCode)// 数组集合
      params.updateIds = updateId
    }
    $.ajax({
        url:root.member.chanageTempSkuForMainCustomerId,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            if(data.errorCode == 0){
              if(relationStatus == 10){
                $.Huimodalalert('添加成功',2000);
                $("#temp-goods").modal("hide");//弹窗消失
                getData.searchTemporaryData();//刷新数据
              }else if(relationStatus == 20){
                $.Huimodalalert('删除成功',2000);
                $("#selectAll").prop("checked",false)
                getData.searchTemporaryData();//刷新数据
              }
            }
        },
        error: function (msg) {
            $.Huimodalalert(msg,2000);
        }
    })
  }
}
//渲染数据
var renderData = {
  // 查询临采数据回填
  tableLists:function(data){
    dataSource = [];
    if(data != null && data != ''){
      var startRow = data.startRow+1;
      $.each(data.data,function(index,item){
        var dataT = startRow++;
        var obj = {};
        obj.skuCode = item.skuCode;//临采sku编码
        obj.oldSkuName = item.oldSkuName;//临采sku名称
        obj.unit = item.unit;//临采sku单位
        obj.poolSetOperateTime = item.poolSetOperateTime;//操作时间
        obj.dataT = dataT;
        dataSource.push(obj)
      })
    }
    renderData.temporaryLists(dataSource)
  },
  // 弹窗---查询临采商品弹窗数据回填
  popTableLists:function(data){
    popDataSource = [];
    if(data != null && data != ''){
      var startRow = data.startRow+1;
      $.each(data.data,function(index,item){
        var dataT = startRow++;
        var obj = {};
        obj.skuCode = item.skuCode;//临采sku编码
        obj.oldSkuName = item.oldSkuName;//临采sku名称
        obj.unit = item.unit;//临采sku单位
        obj.updateIds = item.updateIds;// 选择添加的id
        obj.dataT = dataT;
        popDataSource.push(obj)
      })
    }
    renderData.popLists(popDataSource)
  },
  // 渲染查询临采商品列表渲染
  temporaryLists:function(data){
    var datatable = $("#templists").dataTable(); // 初始化dataTable，清空上一个值
    datatable.fnClearTable();//清空一下table
    datatable.fnDestroy(); //还原初始化了的datatable
    $("#templists").DataTable({
      "order": [[ 1, "desc" ]],
      "autoWidth": false,
      "ordering": false,
      "searching": false,
      "paging": false,
      "retrieve": true,
      "destroy": true,
      "bAutoWidth": true,
      "bLengthChange": true,
      "aLengthMenu": [5, 10, 25, 50],
      "oLanguage": {
        "sLengthMenu": "每页显示 _MENU_ 条记录",
        "sZeroRecords": "抱歉， 没有找到",
        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
        "sInfoEmpty": "",
        "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
        "oPaginate": {
          "sFirst": "首页",
          "sPrevious": "前一页",
          "sNext": "后一页",
          "sLast": "尾页"
        },
        "sZeroRecords": "没有检索到数据",
        /* "sProcessing": "<img src='./loading.gif' />",*/
      },
      data:data,
      columnDefs: [
        {
          "visible": true,
          "targets": 0
        },
        {
          "render": function(data, type, row, meta) {
            /*console.log(row.materielId)*/
            return '<span style="text-align: center;"><td><input  class="selectCheck" type="checkbox" name="checkbox" data-type='+ row.skuCode +'></td></span>';
          },
          "targets": 0
        },
        {
          "render": function(data, type, row, meta) {
            var skuCode = row.skuCode;
            if(skuCode == undefined){
              skuCode = ''
            }
            return '<span style="text-align: center;" >'+skuCode+'</span>';

          },
          "targets": 1
        },
        {
          "render": function(data, type, row, meta) {
            var oldSkuName = row.oldSkuName;
            if(oldSkuName == undefined){
              oldSkuName = ''
            }
            return  '<span style="text-align: center;" >'+ oldSkuName +'</span>';
          },
          "targets": 2
        },
        {
          "render": function(data, type, row, meta) {
            var unit = row.unit;
            if(unit == undefined){
              unit = ''
            }
            return  '<span style="text-align: center;">'+ unit +'</span>';
          },
          "targets": 3
        },
        {
          "render": function(data, type, row, meta) {
            var poolSetOperateTime = row.poolSetOperateTime;
            if(poolSetOperateTime == undefined){
              poolSetOperateTime = ''
            }
            return  '<span style="text-align: center;">'+ poolSetOperateTime +'</span>';
          },
          "targets": 4
        },
        {
          "render": function(data, type, row, meta) {
            return '<span style="text-align: center; color: #0000ff;cursor: pointer" onclick="cancelData(\''+row.skuCode+'\')" >'+'移除'+'</span>' ;
          },
          "targets": 5
        },
      ],
      fnInitComplete:function(){
          $("#templists").on("change",".selectCheck",function(){
            var num = $(".bodyTable").find("input[type=checkbox]:checked").length;
            var selectTotalLength = $(".selectCheck").length;
            if(num == selectTotalLength){
              $("#selectAll").prop("checked",true)
            }else{
              $("#selectAll").prop("checked",false)
            }
          })
      }
    })
  },
  // 弹窗-- 获取临采商品弹窗列表渲染
  popLists: function (data) {
    var datatable = $("#poplists").dataTable(); // 初始化dataTable，清空上一个值
    datatable.fnClearTable();//清空一下table
    datatable.fnDestroy(); //还原初始化了的datatable
    $("#poplists").DataTable({
      //"order": [[ 1, "desc" ]],
      "autoWidth": false,
      "ordering": false,
      "searching": false,
      "paging": false,
      "retrieve": true,
      "destroy": true,
      "bAutoWidth": true,
      "bLengthChange": true,
      "aLengthMenu": [5, 10, 25, 50],
      "oLanguage": {
        "sLengthMenu": "每页显示 _MENU_ 条记录",
        "sZeroRecords": "抱歉， 没有找到",
        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
        "sInfoEmpty": "",
        "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
        "oPaginate": {
          "sFirst": "首页",
          "sPrevious": "前一页",
          "sNext": "后一页",
          "sLast": "尾页"
        },
        "sZeroRecords": "没有检索到数据",
        /* "sProcessing": "<img src='./loading.gif' />",*/
      },
      data:data,
      columnDefs: [
        {
          "visible": true,
          "targets": 0
        },
        {
          "render": function(data, type, row, meta) {
            var skuCode = '<span style="text-align: center;">'+row.skuCode+'</span>';
            return skuCode
          },
          "targets": 0
        },
        {
          "render": function(data, type, row, meta) {
            var skuName = '<span style="text-align: center;">'+row.oldSkuName+'</span>';
            return skuName
          },
          "targets": 1
        },
        {
          "render": function(data, type, row, meta) {
            var unit = '<span style="text-align: center;">'+row.unit+'</span>';
            return unit
          },
          "targets": 2
        },
        {
          "render": function(data, type, row, meta) {
            var select = '<span style="text-align: center; color: blue; cursor: pointer" onclick="select(\''+row.skuCode+'\')">'+'选择'+'</span>';
            return select
          },
          "targets": 3
        },
      ]
    })
  }
}

//反选处理
// 点击查询按钮
function search(){
  getData.searchTemporaryData()
}
// 单个商品删除
function cancelData(skuCode){
  getData.addOrCancel(20,skuCode)
}
// 批量删除 skuCode
function modifyCancel(){
  var params = [];
  $.each($('.selectCheck'),function(index,item){
    if($(this).is(":checked")){
      var skuCode = item.getAttribute("data-type")
      params.push(skuCode);
    }
  });
  getData.addOrCancel(20,params)
  // params如果为空说明没有选择删除对象
  if(params.length <=0){
    $.Huimodalalert("请选择要删除的数据",2000);
  }
}
// 导入按钮
function importExcel(){
  $("#fileUp").trigger('click')
}
// 导入接口接口执行
//getData.importAppointRuleExcel()
// 下载错误值
function errorvalue() {
  $('#errorvalue').attr('href',root.member.excelImportErrorLog+"?operateUserId="+operateUserId+'&moduleType='+ 40);
}

function Imports(){
  var name=$("#fileUp").val();
  var result = /\.[^\.]+/.exec(name);
  if (result != ".xlsx" && result != ".xls") {
    $.Huimodalalert('格式不正确！',2000);
    return false;
  }
  var formData = new FormData();
  formData.append('file', $("#fileUp")[0].files[0]);
  formData.append('operateUserId', operateUserId);
  formData.append('operateUserName',operateUserName);
  formData.append('mainCustomerId',mainCustomerId);
  $.ajax({
    url: root.member.importAppointRuleExcel,
    cache: false,  //禁用缓存
    type: "POST",
    // 告诉jQuery不要去处理发送的数据
    processData: false,
    // 告诉jQuery不要去设置Content-Type请求头
    contentType: false,
    data: formData,
    success: function (data) {
      $('#fileUp').val('');
      if(data.errorCode==0){
        $.Huimodalalert('导入成功！',1000);
        var success_num = data.data.success_num;//导入的成功数
        var error_num = data.data.error_num;//导入的失败数
        if(Number(error_num)>0){
          $("#successnum").text(success_num)
          $("#errornum").text(error_num);
          $("#tipmessage").css({"display":"block"})
          setTimeout(function(){
            $("#tipmessage").css({"display":"none"})
          },5000)
        }
        getData.searchTemporaryData()

      }else if(data.errorCode==1 || data.errorCode==5){
        $.Huimodalalert(data.msg,1000);
      }else {
        $.Huimodalalert('导入失败',1000);
      }

    }
  });
}

// 临采商品添加商品弹窗显示
function addData(){
  $("#popskuCode").val("");
  $("#popskuName").val("");
  var datatable = $("#poplists").dataTable(); // 初始化dataTable，清空上一个值
  datatable.fnClearTable();//清空一下table
  datatable.fnDestroy(); //还原初始化了的datatable
  $(".M-box3").pagination({
    pageCount:0
  });//处理分页
  // 点击弹窗显示
  $("#temp-goods").modal("show");
}
// 弹窗查询按钮
function popSearch(){
  getData.popSearchTemporaryData(20)
}
// 弹窗选择按钮
function select (skuCode){
  getData.addOrCancel(10,skuCode)
}
// 模板下载
function downLoadModel(){
  /*$('#down_load').attr('href','https://t2.fsyuncai.com/api/pc/baseservice/downLoadFromUrl?urlStr=https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20200914162317492762.xlsx&fileName=LC')*/
  $('#down_load').attr('href',root.publics.downLoadFromUrl+'?urlStr=https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20201013162751641151.xlsx&fileName=LC')
}